package com.huohuo.zkcurator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.springframework.stereotype.Component;

//该类中构造函数会进行初始化操作
@Component
public class CuratorOpration {

    public static CuratorFramework curatorFramework = null;

    //集群用逗号，把其他zookeeper的ip和端口加入"192.168.137.3:2181,192.168.137.3:2182,192.168.137.3:2183";
    private static final String ZK_SERVER_CLIENT = "192.168.137.3:2181";

    /**
     * 实例化zk客户端
     */
    public CuratorOpration(){

        /**
         *1.设置重试策略
         *  curator链接zk的重试策略：RetryNTimes
         * n:重试的次数
         * sleepMsBetweenRetries：每次重试间隔秒数
         */
        RetryPolicy retryPolicy = new RetryNTimes( 3,5000 );

        /*
         *2.把重试策略放到客户端中
         */
        curatorFramework = CuratorFrameworkFactory.builder()
                .connectString( ZK_SERVER_CLIENT )  //链接的客户端地址
                .sessionTimeoutMs( 1000 )       //会话超时时间毫秒
                .retryPolicy( retryPolicy )//重试的策略
                .namespace( "workspace" ) //工作空间根节点
                .build();
        /**
         * 3.启动链接
         */
        curatorFramework.start();

    }

    /**
     * 关闭zk客户端
     */
    public void closeZKClient(){
        if (curatorFramework != null){
            this.curatorFramework.close();
        }
    }




}
